package com.bdpn.controller;


import com.bdpn.dto.AppInfoDto;
import com.bdpn.entity.AppInfo;
import com.bdpn.service.AppInfoService;
import com.bdpn.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/appInfo")
public class AppInfoController {
    @Autowired
    AppInfoService appInfoService;

    @PostMapping("/appInfoPage")
    public ResultVo queryPage(@RequestBody AppInfoDto appInfoDto, @RequestParam(defaultValue = "1") Integer pageNum, HttpServletRequest request) {
        String token = request.getHeader("token");
        String[] split = token.split("-");
        String devId = split[2];       //开发者id
        String userType = split[3];    //userType  类型
        if(userType.equals("dev")){    //如果是开发者就带自己的id去查询
            appInfoDto.setDevid(Integer.parseInt(devId));
        }else if(userType.equals("admin")){
            appInfoDto.setStatus(1);
        }
        PageInfo<AppInfo> page = appInfoService.page(appInfoDto, pageNum);
        return ResultVo.success("查询成功", page);
    }

    //新增或修改
    @PostMapping("/saveOrUpdate")
    public ResultVo saveOrUpdate(AppInfo appInfo, MultipartFile file, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (file!=null && !file.isEmpty()) {
            String filename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(filename);
            if (file.getSize() > 1024 * 500) {
                return ResultVo.error("图片大小超过500KB");
            } else if (extension.equalsIgnoreCase("jpg") ||
                    extension.equalsIgnoreCase("gif") ||
                    extension.equalsIgnoreCase("jpeg") ||
                    extension.equalsIgnoreCase("png")
            ) {
                String realPath = request.getServletContext().getRealPath("/upload");
                File file1 = new File(realPath);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
                try {
                    file.transferTo(new File(realPath + "/" + fileName));
                    appInfo.setLogopicpath("/upload/" + fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                    ResultVo.error("文件上传失败");
                }
            } else {
                return ResultVo.error("文件格式错误!");
            }
        }
//        DevUser devUser = (DevUser)SessionUtils.get(token);
        String[] split = token.split("-");
        String userId = split[2];
        if (appInfo.getId() == null) {
            appInfo.setDevid(Integer.parseInt(userId));
            appInfo.setDownloads(0);   //下载量
            appInfo.setCreatedby(Integer.parseInt(userId));   //创建者
            appInfo.setCreationdate(new Date());    //创建时间
            appInfo.setStatus(1);   //状态
        } else {
            appInfo.setStatus(1);
            appInfo.setModifyby(Integer.parseInt(userId));    //更新者
            appInfo.setModifydate(new Date());
        }
        int i = appInfoService.saveOrUpdate(appInfo);
        if (i > 0) {
            return ResultVo.success("操作成功", i);
        }
        return ResultVo.error("操作失败");
    }

    //验证apk是否重复
    @PostMapping(value = "/selectApk")
    public ResultVo OnSelect(String apkName) {
        int i = appInfoService.OnSelect(apkName);
        if(i>0){
            return ResultVo.error("名称重复");
        }else{
            return ResultVo.success("名称可用",null);
        }

    }

    //通过id查看手游信息
    @GetMapping("/selId")
    public ResultVo selectId(Integer id) {
        AppInfo appInfo = appInfoService.selectId(id);
        return ResultVo.success("查询成功", appInfo);
    }

    //删除手游信息
    @DeleteMapping("/{appId}")
    public ResultVo deleteAppId(@PathVariable Integer appId,HttpServletRequest request){
        try {
            appInfoService.del(appId,request);
            return ResultVo.success("删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("删除失败!");
        }
    }

    //上下架app
    @PutMapping("/{id}")
    public ResultVo saleApp(@PathVariable Integer id){
        try {
            appInfoService.saleApps(id);
            return ResultVo.success("操作成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("操作失败");
        }
    }

    //管理员审核app
    @PostMapping("/auditApps")         //通过id修改状态
   public ResultVo auditApp(Integer status,Integer appId){
        AppInfo appInfo = new AppInfo();
        appInfo.setStatus(status);
        appInfo.setId(appId);
        int i = appInfoService.saveOrUpdate(appInfo);
        return ResultVo.success("",i);
    }
}
